package org.ihelpuoo.weboo.tag.core;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.Arrays;

import javax.servlet.jsp.JspException;

import org.ihelpuoo.I;
import org.ihelpuoo.io.FilePatternFilter;
import org.ihelpuoo.lang.StringUtils;
import org.ihelpuoo.parser.segment.Segment;
import org.ihelpuoo.util.cmp.FileNameLengthComparator;
import org.ihelpuoo.weboo.tag.WebooTag;

public abstract class LinkTag extends WebooTag
{

	private static final long	serialVersionUID	= 7378261117048745723L;

	private String				src;
	private int					deep;
	protected String			filter;
	private int					pos;
	protected Segment			seg;

	protected LinkTag()
	{
		deep = -1;
		pos = -1;
	}

	public String getSrc()
	{
		return src;
	}

	public void setSrc(String src)
	{
		this.src = src;
	}

	public int getDeep()
	{
		return deep;
	}

	public void setDeep(int deep)
	{
		this.deep = deep;
	}

	public String getFilter()
	{
		return filter;
	}

	public void setFilter(String filter)
	{
		this.filter = filter;
	}

	@Override
	protected void start() throws JspException
	{
		if (StringUtils.isBlank(src))
			return;
		File f = new File(pageContext.getServletContext().getRealPath(src));
		if (pos < 0)
			pos = f.getAbsolutePath().length() - src.length();
		if (!f.exists())
			return;
		try
		{
			if (f.isFile())
			{
				seg.set("src",formatSource(f));
				pageContext.getOut().write(seg.toString());
			}
			else
			{
				_outputScriptLink(f,0);
			}
		}
		catch (IOException e)
		{
			throw new JspException(e);
		}
	}

	@Override
	protected void end() throws JspException
	{
	}

	private void _outputScriptLink(File f, int step) throws IOException
	{
		if (deep >= 0 && step > deep)
			return;
		FileFilter ff = FilePatternFilter.getInstance(filter);
		File[] list = f.listFiles();
		Arrays.sort(list,new FileNameLengthComparator());
		// ouput current folder
		for (int i = 0; i < list.length; i++)
			if (list[i].isFile() && (ff == null || ff.accept(list[i])))
			{
				seg.set("src",formatSource(list[i]));
				pageContext.getOut().write(seg.toString());
				pageContext.getOut().write(I.NEW_LINE);
			}
		// output sub-folder
		for (int i = 0; i < list.length; i++)
			if (list[i].isDirectory())
				_outputScriptLink(list[i],step + 1);
	}

	private String formatSource(File f)
	{
		return getContextPath() + f.getAbsolutePath().substring(pos).replaceAll("\\\\","/");
	}
}
